<template>
	<view class="bg"></view>
	<view class="" :style="{height: menuTopHeight + 'px'}"></view>
	<view class="menu-box" :style="{height: menuHeight + 'px'}" @tap="goPosition">
		<view style="margin-right: 20rpx;">{{ hospitalStore.name }}</view>
		<u-icon name="arrow-down-fill" color="#fff" size="10"></u-icon>
		<!-- <u-image width="120rpx" height="38rpx" src="/static/images/logo.png"></u-image> -->
	</view>
	<!-- 搜索 -->
	<view class="container">
		<view class="search-box">
			<u-search placeholder="搜索医生..." v-model="keyword" :showAction="false" @search="handleSearch"></u-search>
			<!-- <view style="margin: 0 20rpx 0 24rpx;">
				<u-image width="80rpx" height="80rpx" src="/static/images/a1.png" @click="scanHandle"></u-image>
			</view> -->
			<view class="" style="margin-left: 20rpx;">
                <u-image width="80rpx" height="80rpx" :src="getServerStatic('/static/images/a1.png')"  @click="scanHandle"></u-image>

<!--				<u-image width="80rpx" height="80rpx" src="/static/images/a2.png" @click="showPhone = true"></u-image>-->
			</view>
		</view>
		<!-- 轮播 -->
		<view class="swiper-box">
			<u-swiper height="262rpx" :list="swiperList"></u-swiper>
		</view>
		<!-- 公告 -->
		<view class="notice-box">
			<u-image width="54rpx" height="32rpx" :src="getServerStatic('/static/images/a3.png')"></u-image>
			<view>/</view>
			<u-notice-bar fontSize="22rpx" icon="" color="#516DDB" bgColor="transparent" :text="notice"></u-notice-bar>
		</view>
		<!-- 金刚区 -->
		<view class="navigate-box">
			<u-grid :border="false" col="3" @click="navigateChange">
				<u-grid-item>
					<view class="item">
						<u-image width="222rpx" height="170rpx" :src="getServerStatic('/static/images/a51.png')" ></u-image>
					</view>
				</u-grid-item>
				<u-grid-item>
					<view class="item">
						<u-image width="222rpx" height="170rpx" :src="getServerStatic('/static/images/a52.png')"></u-image>
					</view>
				</u-grid-item>
				<u-grid-item>
					<view class="item">
						<u-image width="222rpx" height="170rpx" :src="getServerStatic('/static/images/a53.png')"></u-image>
					</view>
				</u-grid-item>
			</u-grid>
		</view>
		<!-- 会员储值 -->
		<view class="vip-box" @tap="goVip">
			<u-image width="100%" height="110rpx" :src="getServerStatic('/static/images/b5.png')" ></u-image>
		</view>
		<!-- 预约中心展示 -->
		<view class="center-box">
			<swiper style="height: 246rpx;width: 100%;" :indicator-dots="false" :autoplay="true">
				<swiper-item style="height: 246rpx;">
					<view class="card-item" @tap="goHospital">
						<u-image width="210rpx" radius="10rpx" height="210rpx" :src="checkAndFixUrl(hospitalStore.photo)" ></u-image>
						<view class="card-content">
							<view class="title">{{ hospitalStore.name }}</view>
							<view class="address">{{ hospitalStore.address }}</view>
							<view class="mobile-box">
								<view class="mobile">电话：{{ hospitalStore.hotline }}</view>
								<view class="map-box" @tap.stop="showHospitalMap">
									<u-image width="20rpx" height="20rpx" :src="getServerStatic('/static/images/a19.png')" ></u-image>
									<view>导航</view>
								</view>
							</view>
						</view>
					</view>
				</swiper-item>
			</swiper>
		</view>
		<!-- 推荐 -->
		<view class="suggest-box">
			<view class="title-wrap">
				<view class="title">医生推荐</view>
				<view class="more-box" @tap="navigateToReservationFormDoctor(0)">
					<text>查看全部</text>
					<u-icon name="arrow-right" color="#91959E" size="14"></u-icon>
				</view>
			</view>
			<scroll-view scroll-x="true" class="suggest-scroll">
				<view class="scroll-list">
					<view class="item" v-for="(item, i) in recommendDoctorList" :key="i">
						<!-- 头像 -->
						<view class="avatar-box">
							<u-avatar :src="item.avatar" size="110rpx"></u-avatar>
							<view>{{ item.name }}</view>
						</view>
						<!-- 预约按钮 -->
						<view class="btn">
							<u-button throttleTime="1000" :customStyle="{height: '56rpx', letterSpacing: '.1rem'}" :hairline="false"
                                      type="mini" shape="circle" color="linear-gradient(315deg, #4975EC 0%, #97B3FF 100%)"
                                      @click="navigateToReservationFormDoctor(item.id)">立即预约</u-button>
						</view>
						<view class="tag-box">
							<view class="tag">{{item.job_title }} {{item.department_name}}</view>
							<view class="intro">{{item.desc}}</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>

	<!-- 客服电话 -->
	<u-action-sheet round="30rpx" :show="showPhone" :actions="actions" title="" description="" @close="showPhone = false"
		@select="callConfirm">
	</u-action-sheet>
	<TabBar :current-page="0"></TabBar>
</template>

<script setup>
    import {ref, reactive, readonly} from "vue"
    import {onLoad, onShow} from '@dcloudio/uni-app'
    import TabBar from "@/components/Tabbar"
	import {useHeight} from '@/hooks/useMenuHeight'
	const {menuHeight, menuTopHeight} = useHeight()
    import {getBanner, getHomeDepartments, getNotice} from "@/api/cms"
    import {getRecommend} from "@/api/doctor"
    import {checkAndFixUrl, getServerStatic} from "@/utils/tool"
    import {useHospitalStore, useSystemStore, useUserStore} from '@/store';
    import {setCache} from "@/utils/cache";
    import {verifyQrCode} from "@/api/partner";

    // 医院store
    const hospitalStore = useHospitalStore()

    const systemStore = useSystemStore()

    // 用户store
    const userStore = useUserStore();

    // const hospitalStore = ref({
	// 	photo: '',
	// 	name: '浑南区诊室',
	// 	address: '青年大街',
	// 	hotline: '17640101265'
	// })


	const keyword = ref('')
    // 公告
	const notice = ref('12月27日梁主任免费大堂义诊数量预约有限')
	// 轮播图
	const swiperList = ref([
		// 'https://cdn.uviewui.com/uview/swiper/swiper1.png',
		// 'https://cdn.uviewui.com/uview/swiper/swiper2.png',
		// 'https://cdn.uviewui.com/uview/swiper/swiper3.png',
	])

    // 分类
    const navigateList = ref([
        {
            name: '取药提醒',
            href: '/mine/dispensary/list',
            icon: '/static/images/a7.png'
        }
    ])

    // 医生推荐
    const recommendDoctorList = ref([
		{ avatar: '', name: '王医生', id: 1, job_title: '主任医师', department_name: '中医内科', desc: '描述' }
	])

    onLoad((evt) => {
        console.log('home on load', evt)
        // 邀请上级用户
        if (evt?.superior) {
            console.log('superior',evt.superior)
            setCache('superior', evt.superior)
        }
        handleGetHospital()
        handleGetSystem()
        handleGetNotice()
    })

    onShow( () => {
        console.log('on show')
        // 门店id存在
        if (hospitalStore.id && hospitalStore.id > 0) {
            handleGetRecommendDoctors()
        } else {
            setTimeout(() => {
                handleGetRecommendDoctors()
            },1500)
        }

        handleGetBanner()
    })

    // 获取banner.
    const handleGetBanner = async () => {
        const result = await getBanner({})
        if (result.code === 1) {
            swiperList.value = result.data.map(item => {
                return checkAndFixUrl(item.banner)
            })
        }
    }

    // 获取医院详情
    const handleGetHospital = async () => {
        hospitalStore.handleGetHospital();
    }

    // 获取系统配置
    const handleGetSystem = async () => {
        systemStore.handleGetSystemConf()
    }

    // 获取公告
    const handleGetNotice = async () => {
        const {code, data, message} = await getNotice({})
        if (code === 1) {
            notice.value = data?.content ?? ''
        }
    }


    // 获取推荐医生.
    const handleGetRecommendDoctors = async () => {
        let store_id = hospitalStore.id
        console.log('获取推荐医生', hospitalStore.name)
        const {code, data, message} = await getRecommend({store_id: store_id})
        if (code == 1) {
            recommendDoctorList.value= data.map(item => {
                return {
                    ...item,
                    avatar: checkAndFixUrl(item?.avatar ?? ''),
                }
            })
        }
    }

    const toLogin = () => {
        uni.showToast({
            mask: true,
            title: '请先登录!',
            icon: 'error'
        })
        const pages = getCurrentPages()
        let fromPath = "/" + pages[pages.length - 1].route
        setTimeout(() => {
            // @ts-ignore
            uni.redirectTo({
                url: "/pages/login/login?fromPath=" + encodeURIComponent(fromPath)
            });
        },800)
    }

	// 扫码
	const scanHandle = () => {
        if (!userStore.token) {
            toLogin()
            return false;
        }
        // @ts-ignore
		uni.scanCode({
			success: (res) => {
                console.log('扫码内容:',res);
                let value = res?.result ?? ''
                if (value.length <= 0) {
                    uni.showModal({
                        title: '提示',
                        content: "扫码失败,获取内容为空",
                        showCancel: false,
                        success: function (res) {
                            if (res.confirm) {
                                console.log('用户点击确定');
                            } else if (res.cancel) {
                                console.log('用户点击取消');
                            }
                        }
                    });
                    return false;
                }
                handleVerifyQrCode(value)
			}
		})
	}

    const handleVerifyQrCode = async (value) => {
        uni.showLoading({
            title: '请求中'
        });
        try {
            const {code, data, message} = await verifyQrCode({hash: value})
            uni.hideLoading();
            if (code == 1) {
                uni.showToast({
                    mask: true,
                    title: '扫码成功',
                    icon: 'success'
                })
            } else {
                uni.showModal({
                    title: '提示',
                    content: message ?? "失败",
                    showCancel: false,
                    success: function (res) {
                        if (res.confirm) {
                            console.log('用户点击确定');
                        } else if (res.cancel) {
                            console.log('用户点击取消');
                        }
                    }
                });
            }
        } catch (e) {
            uni.hideLoading()
            console.error(e)
        }
    }

    // 客服
    const showPhone = ref(false)
    const actions = ref([{
        name: `一键拨打：${systemStore.customer}`,
        isCall: true
    },
        {
            name: '取消',
            isCall: false
        },
    ])
    // 拨打电话
    const callConfirm = e => {
        console.log(e);
        if (e.isCall) {
            uni.makePhoneCall({
                phoneNumber: systemStore.customer
            })
        }
    }

    // 搜索
    const handleSearch = () => {
        console.log(keyword.value)
        uni.navigateTo({
            url: `/mine/reservation/reservation?doctor_name=${keyword.value}`
        })
    }

	// 金刚区跳转
	const navigateChange = (e) => {
        console.log(e);
		// 预约挂号
		if (e == 0) {
			uni.navigateTo({
			    url: '/mine/reservation/reservation'
			})
		}
		// 电子病历
		else if (e == 1) {
			uni.navigateTo({
			    url: '/mine/medical/list'
			})
		}
		// 药品货庄
		else if (e == 2) {
			uni.navigateTo({
			    url: '/pages/home/home'
			})
		}
        // if (e.href === '/mine/dispensary/list') {
        //     uni.navigateTo({
        //         url: '/mine/dispensary/list'
        //     })
        // }
        // // 分类列表
        // if (e?.child_exists) {
        //     // 存在下级 跳转二级分类页
        //     uni.navigateTo({
        //         url: '/mine/project/project'
        //     })
        // } else {
        //     uni.navigateTo({
        //         url: '/mine/reservation/reservation'
        //     })
        // }
	}
	const goHospital = () => {
		uni.switchTab({
			url: '/pages/hospital/hospital'
		})
	}

    // 地图跳转.
    const showHospitalMap = () => {
        console.log("纬度范围为-90~90", hospitalStore.latitude_val)
        console.log("经度范围为-180~180", hospitalStore.longitude_val)
        uni.openLocation({
            latitude: Number(hospitalStore.latitude_val),
            longitude: Number(hospitalStore.longitude_val),
            //longitude: Number(123.536525),
            //latitude: Number(41.74164),
            name: hospitalStore.name,
            address: hospitalStore.address,
            scale: 18,
            success: function () {
                console.log('success');
            },
            fail: function (err) {
                console.log(err);
            }
        });
    }

    const navigateToReservationFormDoctor = (doctorId) => {
        console.log('doctor_id', doctorId)
        uni.navigateTo({
            url: `/mine/reservation/reservation?doctor_id=${doctorId}`
        })
    }

	const goProject = () => {
		uni.navigateTo({
			url: '/mine/project/project'
		})
	}
	// 定位
	const goPosition = () => {
		uni.navigateTo({
			url: '/mine/address/position'
		})
	}
	// 充值会员
	const goVip = () => {
		uni.navigateTo({
			url: '/mine/vip/vip'
		})
	}
</script>

<style lang="scss" scoped>
	.menu-box {
		padding-left: 26rpx;
		color: #fff;
		display: flex;
		align-items: center;
	}
	.bg {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 483rpx;
		background: linear-gradient(180deg, #3165DE 0%, #3165DE 31%, rgba(255, 255, 255, 0.52) 100%);
		border-radius: 0rpx 0rpx 80rpx 80rpx;
		z-index: -1;
	}

	.container {
		padding: 28rpx 24rpx 200rpx;
	}

	.search-box {
		display: flex;
		align-items: center;
	}

	.swiper-box {
		margin-top: 20rpx;
	}

	.notice-box {
		@include start(100%);
		margin-top: 26rpx;
		background: #DFE9FF;
		border-radius: 10rpx;
		padding: 0 14rpx;

		&>view {
			margin-bottom: 6rpx;
			color: #516DDB;
			font-size: 24rpx;
			margin-left: 12rpx;
		}
	}

	.vip-box {
		margin-top: 40rpx;
	}

	.navigate-box {
		margin-top: 40rpx;
		// padding: 44rpx 10rpx 32rpx;
	}

	.center-box {
		height: 246rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		margin-top: 40rpx;
		overflow: hidden;

		.card-item {
			@include between(100%, 100%);
			padding: 18rpx;

			.card-content {
				flex: 1;
				margin-left: 22rpx;

				.title {
					@include over-ellip(450rpx);
					font-size: 34rpx;
					color: #222222;
				}

				.address {
					@include over-ellip(400rpx);
					margin-top: 14rpx;
					font-size: 26rpx;
					color: #606672;
				}

				.mobile-box {
					@include between();
					margin-top: 56rpx;

					.mobile {
						font-size: 24rpx;
						color: #606672;
					}

					.map-box {
						@include center();
						font-size: 24rpx;
						color: #516DDB;
						padding-right: 20rpx;

						&>view {
							margin-left: 12rpx;
						}
					}
				}
			}
		}
	}

	.suggest-box {
		position: relative;
		margin-top: 40rpx;

		.title-wrap {
			@include between(100%);
			margin-bottom: 50rpx;
			.title {
				font-size: 36rpx;
				color: #222222;
			}

			.more-box {
				@include center();

				text {
					font-size: 30rpx;
					color: #606672;
				}
			}
		}
		.suggest-scroll {
			white-space: nowrap;
			height: 270rpx;
			position: relative;
			width: 100%;
			display: flex;
			.scroll-list {
				display: flex;
				position: absolute;
				left: 0;
				top: 14rpx;
				.item {
					position: relative;
					width: 292rpx;
					height: 240rpx;
					background: #FFFFFF;
					border-radius: 20rpx;
					margin-right: 20rpx;
					z-index: 99;
					.avatar-box {
						@include center(100%);
						position: absolute;
						top: -14rpx;
						left: 0;
						font-size: 36rpx;
						color: #222222;
						z-index: 99;
						& > view {
							margin-left: 16rpx;
						}
					}
					.btn {
						width: 210rpx;
						height: 56rpx;
						position: absolute;
						left: 28rpx;
						bottom: -16rpx;
						z-index: 99;
					}
					.tag-box {
						padding: 106rpx 28rpx 94rpx;
						.tag {
							font-size: 28rpx;
							color: #516DDB;
						}
						.intro {
							margin-top: 4rpx;
							font-size: 24rpx;
							color: #606672;
							@include over-ellip();
						}
					}
				}
			}
		}
	}
</style>
